import myAxios from '../myAxios/myAxios.js';
import myAxios28 from '../myAxios/myAxios28.js';

import myArr from '../myAxios/myArr.js';
let { GetNumber } = myArr;
let GetClearDiffence = async function (metCodeParamString) {

	// 1. 调用SAP接口获取数据
	let TYPE;
	try {
		// 注意：原C#代码中调用的是 "SAP_R032_02" 接口
		TYPE = await myAxios.getSap("SAP_R032_02", `Q902🈹${metCodeParamString}`, "9911", "QD");
	} catch (error) {
		console.error("调用SAP接口获取数据失败:", error);
		throw error; // 或返回空数组 []
	}

	// 2. 提取DataTable (假设TYPE.TableSet['IT_DATA']是对象数组)
	let table = TYPE.TableSet['IT_DATA'];
	if (!table || !Array.isArray(table)) {
		console.warn("从SAP接口获取的数据无效或不是数组");
		return [];
	}

	// 3. 按物料号(MATNR)分组，并计算每个组的CYMNG和REMNG总和
	const groupedMap = {}; // 使用对象进行分组聚合

	for (const row of table) {
		const matnr = row['MATNR']; // 物料号
		const cymng = GetNumber(row.CYMNG); // CYMNG, 转换为整数，失败则为0
		const remng = GetNumber(row.REMNG); // REMNG, 转换为整数，失败则为0

		if (!groupedMap[matnr]) {
			groupedMap[matnr] = {
				MATNR: matnr,
				CLEAR_DIFFERENCE: 0, // CYMNG 总和
				RSMNG: 0,  // REMNG 总和
			};
		}
		groupedMap[matnr]['CLEAR_DIFFERENCE'] += cymng;
		groupedMap[matnr]["RSMNG"] += remng;
	}

	// 4. 将分组对象转换为数组
	let dtGroupBy = Object.values(groupedMap);

	// 5. 返回最终结果
	console.log('毛差异 和 预留 :>> ', dtGroupBy);
	return dtGroupBy;
};
export {
	GetClearDiffence
};